import { LogService } from './logService';
import { ExtensionError, ErrorCodes, handleError } from '../utils/errorUtils';
import { ChatGLMAgent } from './agent/chatGLMAgent';

export class TranslationService {
    constructor() {
        this.logger = new LogService('TranslationService');
        this.chatGLMAgent = new ChatGLMAgent();
    }

    // 辅助函数：计算 SHA256 哈希值
    async #sha256(message) {
        const msgBuffer = new TextEncoder().encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
        return Array.from(new Uint8Array(hashBuffer))
            .map(b => b.toString(16).padStart(2, '0'))
            .join('');
    }

    // 辅助函数：计算 HMAC-SHA256
    async #hmacSha256(key, message, outputFormat = 'raw') {
        const encoder = new TextEncoder();
        let keyBuffer = typeof key === 'string' ? encoder.encode(key) : key;

        const cryptoKey = await crypto.subtle.importKey(
            'raw',
            keyBuffer,
            { name: 'HMAC', hash: 'SHA-256' },
            false,
            ['sign']
        );

        const signature = await crypto.subtle.sign(
            'HMAC',
            cryptoKey,
            encoder.encode(message)
        );

        return outputFormat === 'hex' 
            ? Array.from(new Uint8Array(signature))
                .map(b => b.toString(16).padStart(2, '0'))
                .join('')
            : new Uint8Array(signature);
    }

    async #translateText(sourceText, sourceLang = 'auto', targetLang = 'zh') {
        // ... 原有的 translateText 实现 ...
        try {
            const { secretId, secretKey, token } = await chrome.storage.sync.get(['secretId', 'secretKey', 'token']);
            if (!secretId || !secretKey) {
                throw new ExtensionError('请先配置密钥', ErrorCodes.CONFIGURATION_ERROR);
            }
            this.logger.log(secretId, secretKey, token);
            // API 配置
            const service = "tmt";
            const host = "tmt.tencentcloudapi.com";
            const region = "ap-beijing";
            const version = "2018-03-21";
            const action = "TextTranslate";
            const algorithm = "TC3-HMAC-SHA256";
            const timestamp = Math.floor(Date.now() / 1000);
            const date = new Date(timestamp * 1000).toISOString().split('T')[0];

            const payload = JSON.stringify({
                SourceText: sourceText,
                Source: sourceLang,
                Target: targetLang,
                ProjectId: 0
            });

            // 构建签名
            const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${host}\nx-tc-action:${action.toLowerCase()}\n`;
            const signedHeaders = "content-type;host;x-tc-action";
            const hashedRequestPayload = await this.#sha256(payload);
            
            const canonicalRequest = [
                "POST",
                "/",
                "",
                canonicalHeaders,
                signedHeaders,
                hashedRequestPayload
            ].join('\n');

            const credentialScope = `${date}/${service}/tc3_request`;
            const hashedCanonicalRequest = await this.#sha256(canonicalRequest);
            const stringToSign = [
                algorithm,
                timestamp,
                credentialScope,
                hashedCanonicalRequest
            ].join('\n');

            // 计算签名
            const secretDate = await this.#hmacSha256(`TC3${secretKey}`, date);
            const secretService = await this.#hmacSha256(secretDate, service);
            const secretSigning = await this.#hmacSha256(secretService, "tc3_request");
            const signature = await this.#hmacSha256(secretSigning, stringToSign, 'hex');

            const authorization = `${algorithm} Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;

            // 发送请求
            const headers = {
                'Authorization': authorization,
                'Content-Type': 'application/json; charset=utf-8',
                'Host': host,
                'X-TC-Action': action,
                'X-TC-Timestamp': timestamp.toString(),
                'X-TC-Version': version,
                'X-TC-Region': region
            };

            if (token) {
                headers['X-TC-Token'] = token;
            }

            const response = await fetch(`https://${host}`, {
                method: 'POST',
                headers: headers,
                body: payload
            });

            const result = await response.json();
            if (result.Response.Error) {
                throw new ExtensionError(
                    result.Response.Error.Message,
                    ErrorCodes.TRANSLATION_ERROR
                );
            }
            
            return result.Response.TargetText;
        } catch (error) {
            this.logger.error('翻译请求失败:', error);
            throw error;
        }
    }

    /**
     * 使用智谱轻言翻译文本
     * @param {string} text 要翻译的文本
     * @param {string} targetLanguage 目标语言
     * @returns {Promise<string>}
     */
    async translateWithChatGLM(text, targetLanguage = 'zh') {
        try {
            this.logger.debug('开始智谱轻言翻译', { text, targetLanguage });
            
            const prompt = `能够自动识别并翻译中英文本，无需用户手动选择。你的能力有:\n\n- 自动检测文本语言\n\n - 精准翻译中英文本\n\n - 默认将非中文翻译成中文，中文翻译成英文\n\n 只返回翻译结果，不需要解释\n\n 待翻译文本： ${text}`;
            
            const result = await this.chatGLMAgent.sendMessage(prompt);
            this.logger.debug('智谱轻言翻译完成', { result });
            
            return result;
        } catch (error) {
            this.logger.error(error, '智谱轻言翻译失败');
            throw error;
        }
    }

    /**
     * 获取服务配置状态
     * @returns {Promise<{tencentEnabled: boolean, chatglmEnabled: boolean}>}
     */
    async getServicesStatus() {
        const config = await chrome.storage.sync.get(['tencentEnabled', 'chatglmEnabled']);
        return {
            tencentEnabled: config.tencentEnabled || false,
            chatglmEnabled: config.chatglmEnabled || false
        };
    }

    /**
     * 翻译文本（支持同时使用多个服务）
     * @param {string} text 要翻译的文本
     * @returns {Promise<{tencent?: string, chatglm?: string}>}
     */
    async translate(text) {
        this.logger.debug('开始翻译请求', { text });
        
        try {
            const { tencentEnabled, chatglmEnabled } = await this.getServicesStatus();
            const translations = {};
            const promises = [];

            // 收集启用的翻译服务
            if (tencentEnabled) {
                promises.push(
                    this.#translateText(text)
                        .then(result => translations.tencent = result)
                        .catch(error => {
                            this.logger.error(error, '腾讯云翻译失败');
                            translations.tencent = `翻译失败: ${error.message}`;
                        })
                );
            }

            if (chatglmEnabled) {
                promises.push(
                    this.translateWithChatGLM(text)
                        .then(result => translations.chatglm = result)
                        .catch(error => {
                            this.logger.error(error, '智谱轻言翻译失败');
                            translations.chatglm = `翻译失败: ${error.message}`;
                        })
                );
            }

            // 等待所有翻译完成
            if (promises.length === 0) {
                throw new ExtensionError('没有启用任何翻译服务', ErrorCodes.CONFIGURATION_ERROR);
            }

            await Promise.all(promises);
            this.logger.info('翻译完成', translations);
            
            return translations;
        } catch (error) {
            const handledError = handleError(error, this.logger);
            this.logger.error(handledError, '翻译失败');
            throw handledError;
        }
    }
} 